package com.pbase.data.http;

import android.content.Context;
import android.text.TextUtils;

import java.util.HashMap;
import java.util.Map;

import androidx.fragment.app.Fragment;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.observers.DisposableObserver;

/**
 * Created by apple on 18/7/17.
 * 请求清理工具
 */
public class RequestObserverControl {
    private static volatile RequestObserverControl mSelf;
    private Map<String, CompositeDisposable> disposableMap=new HashMap<>();
    private RequestObserverControl(){
    }

    public static  RequestObserverControl getInstance(){
        synchronized (RequestObserverControl.class){
            if(mSelf==null){
                mSelf = new RequestObserverControl();
            }
            return mSelf;
        }
    }
    //CompositeDisposable不做全局单例，只根据tag复用
    //即：按mvp的思路，每个页面传入的tag不同，所以CompositeDisposable对于各自的界面是复用的
    public void addSubscription(String tag, DisposableObserver observer){
        CompositeDisposable disposable = disposableMap.get(tag);
        if(disposable==null){
            disposable = new CompositeDisposable();
            disposableMap.put(tag,disposable);
        }
        disposable.add(observer);
    }

    public void cancelAll(String requestTag){
        if(TextUtils.isEmpty(requestTag))
            return;
        CompositeDisposable disposable = disposableMap.get(requestTag);
        if(disposable!=null){
            disposable.dispose();
            disposableMap.remove(requestTag);
        }
    }

    public void cancelAll(Context context){
        String requestTag = "";
        if(context!=null){
            requestTag = context.getClass().getSimpleName();
        }
        cancelAll(requestTag);
    }
    public void cancelAll(Fragment context){
        String requestTag = "";
        if(context!=null){
            requestTag = context.getClass().getSimpleName();
        }
        cancelAll(requestTag);
    }
}
